import 'dart:collection';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/manager/edittext_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/multi_select_class_course_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/multi_select_department_widget.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/bean/punch_in_rule_bean.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/bean/set_punch_rule_response.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/set_rule/set_punch_in_rule_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';

import '../punch_in_rule_list_widget.dart';
import 'common_rule_widget.dart';

///设置考勤规则
class SetPunchInRulePage extends StatefulWidget {
  final bool isGeneral;
  final String type;

  ///考勤规则数据
  final PunchInRuleBean punchInRuleBean;
  static const String ROUTER = "SetPunchInRulePage";

  static Future<bool> navigatorPush(BuildContext context, String type,
      bool isGeneral, PunchInRuleBean punchInRuleBean) {
    ArgumentError.checkNotNull(punchInRuleBean);
    return RouterUtils.routeForFutureResult<bool>(
      context,
      SetPunchInRulePage(
        isGeneral: isGeneral ?? true,
        type: type ?? PunchInRuleListWidget.TYPE_STAFF,
        punchInRuleBean: punchInRuleBean,
      ),
      routeName: SetPunchInRulePage.ROUTER +
          (isGeneral ?? true ? '通用' : "自定义") +
          (type == PunchInRuleListWidget.TYPE_STAFF ? "员工" : "学员"),
    );
  }

  const SetPunchInRulePage(
      {Key key, this.isGeneral, this.type, this.punchInRuleBean})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    if (isGeneral ?? true) {
      return SetGeneralPunchInRulePageState();
    }
    return SetCustomizePunchInRulePageState();
  }

  ///设置员工
  bool isStaff() {
    return PunchInRuleListWidget.TYPE_STAFF == type;
  }
}

///设置通用打开规则
class SetGeneralPunchInRulePageState extends BaseState<SetPunchInRulePage> {
  ValueNotifier<bool> canCommitStatusNotifier;
  SetPunchInRuleViewModel viewModel;

  @override
  void initState() {
    viewModel = SetPunchInRuleViewModel(this);
    super.initState();
    viewModel.editGeneralRuleResult.addListener(() {
      RouterUtils.pop(context, result: true);
    });
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: [
            VgTopBarWidget(
                isShowBack: true,
                title: widget.isStaff() ? "员工·通用规则" : "学员·通用规则"),
            punchInDate(),
            SizedBox(
              height: 10,
            ),
            Expanded(
              child: CommonRuleWidget(
                bean: widget.punchInRuleBean,
                onDeleteClick: () async {
                  bool result =
                      await CommonConfirmCancelDialog.navigatorPushDialog(
                    context,
                    content: '确认删除该考勤规则',
                    confirmText: '删除',
                    confirmBgColor:
                        ThemeRepository.getInstance().getMinorRedColor_F95355(),
                  );
                  if(result??false){
                    PunchInRuleBean emptybean = PunchInRuleBean();
                    emptybean.id = widget.punchInRuleBean.id;
                    emptybean.delflg = "01";
                    emptybean.type = PunchInRuleType.general;
                    viewModel.editGeneralRule(emptybean);
                  }
                },
                onSaveClick: () {
                  viewModel.editGeneralRule(widget.punchInRuleBean);
                },
              ),
            ),
          ],
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///考勤日期
  Container punchInDate() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: EditTextWidget(
        title: "考勤日期",
        hintText: "请输入",
        initContent: "国家规定工作日（周一二三四五）",
        readOnly: true,
        onChanged: (String editText, dynamic value) {
          // uploadBean.relativeStuIds = value;
        },
      ),
    );
  }
}

///设置自定打卡规则
class SetCustomizePunchInRulePageState extends BaseState<SetPunchInRulePage> {
  bool isLightUp = false;
  ValueNotifier<bool> canCommitStatusNotifier;
  SetPunchInRuleViewModel viewModel;

  @override
  void initState() {
    super.initState();
    viewModel = SetPunchInRuleViewModel(this);
    canCommitStatusNotifier = ValueNotifier(false);
    widget.punchInRuleBean.addListener(() {
      canCommitStatusNotifier.value = widget.punchInRuleBean.canCommit();
    });
    viewModel.deleteRuleResult.addListener(() {
      RouterUtils.pop(context, result: true);
    });
    viewModel.repeatNotifier.addListener(() async {
      List<RepeatBean> repeatList = viewModel.repeatNotifier.value;
      if (repeatList != null && repeatList.length > 0) {
        ///包含重复的数据
        String repeatName =
            repeatList.map((e) => e.department).toList().join('、');
        bool result = await CommonConfirmCancelDialog.navigatorPushDialog(
            context,
            title: "提示",
            contentWidget: Expanded(
              child: RichTextWidget(
                  fontSize: 14,
                  overFlow: TextOverflow.visible,
                  height: 1.5,
                  contentMap: LinkedHashMap.from({
                    repeatName ?? '':
                        ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    '已设置个性化考勤规则，是否用新规则覆盖？':
                        ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                  })),
            ),
            content: "$repeatName已设置个性化考勤规则，是否用新规则覆盖？",
            cancelText: "取消",
            confirmText: "覆盖",
            confirmBgColor:
                ThemeRepository.getInstance().getPrimaryColor_1890FF());
        if (result ?? false) {
          widget.punchInRuleBean.cover = true;
          widget.punchInRuleBean.coverid =
              repeatList.map((e) => e.departmentid).toList().join(',');
          viewModel.addRule(widget.punchInRuleBean);
        }
      } else {
        RouterUtils.pop(context, result: true);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: [
            VgTopBarWidget(isShowBack: true, title: "个性化规则"),
            punchInRuleName(),
            _toSplitLineWidget(),
            suitablePeople(),
            _toSplitLineWidget(),
            punchInDate(),
            SizedBox(
              height: 10,
            ),
            Expanded(
              child: CommonRuleWidget(
                bean: widget.punchInRuleBean,
                onDeleteClick: () async{
                  bool result =
                      await CommonConfirmCancelDialog.navigatorPushDialog(
                    context,
                    content: '确认删除该考勤规则',
                    confirmText: '删除',
                    confirmBgColor:
                    ThemeRepository.getInstance().getMinorRedColor_F95355(),
                  );
                  if(result??false){
                    viewModel.delete(widget.punchInRuleBean);
                  }
                },
                onSaveClick: () {
                  viewModel.addRule(widget.punchInRuleBean);
                },
              ),
            ),
          ],
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///规则命名
  Container punchInRuleName() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: EditTextWidget(
        title: "规则命名",
        hintText: "请输入规则名称",
        initContent: widget.punchInRuleBean.name,
        maxZHCharLimit: 30,
        onChanged: (String editText, dynamic value) {
          widget.punchInRuleBean.name = editText;
        },
      ),
    );
  }

  ///考勤日期
  Container punchInDate() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: EditTextWidget(
        title: "考勤日期",
        hintText: "请输入考勤日期",
        initContent: "国家规定工作日（周一二三四五）",
        readOnly: true,
        onChanged: (String editText, dynamic value) {
          // uploadBean.relativeStuIds = value;
        },
      ),
    );
  }

  ///适用对象
  Container suitablePeople() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: EditTextWidget(
        title: "适用对象",
        hintText: "请选择",
        initContent: widget.punchInRuleBean.suitableObjectName ?? '',
        isShowGoIcon: true,
        onTap: (String editText, dynamic value) {
          if (widget.type == PunchInRuleListWidget.TYPE_STAFF) {
            //员工进部门
            return MultiSelectDepartmentWidget.navigatorPush(context,
                selectIds: widget.punchInRuleBean.suitableObjectIds,
                multiSelect: true);
          } else {
            //学员进班级
            return MultiSelectClassCourseWidget.navigatorPush(
                context, widget.punchInRuleBean.suitableObjectIds);
          }
        },
        onDecodeResult: (dynamic result) {
          if (result is! EditTextAndValue) {
            return null;
          }
          return result;
        },
        onChanged: (String editText, dynamic value) {
          widget.punchInRuleBean.suitableObjectIds = value;
          widget.punchInRuleBean.suitableObjectName = editText;
        },
      ),
    );
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: const EdgeInsets.only(left: 15),
      height: 0.5,
      child: Container(
        color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      ),
    );
  }
}
